<template>
  <BasicDrawer
    v-bind="$attrs"
    :isDetail="true"
    :title="drawerTitle"
    :destroyOnClose="true"
    @register="register"
    @visible-change="handleVisibleChange"
  >
    <div class="rules-box">
      <div class="menu">
        <div
          class="menu-item"
          :class="selectedKey === item.key ? 'menu-item-act' : ''"
          v-for="item in items"
          :key="item.key"
          @click="handleMenuClick(item.key)"
          >{{ item.label }}</div
        >
      </div>
      <div class="form-box">
        <!-- 模拟量 -->
        <template v-if="selectedKey === '1'">
          <!-- 限值 -->
          <limitValue ref="limitValueRef" />
          <!-- 定值 -->
          <fixedValue ref="fixedValueRefBySimulation" />
          <!-- 偏差 -->
          <deviation ref="deviationRef" />
          <!-- 变化率 -->
          <changeRateForm ref="changeRateFormRef" />
        </template>
        <!-- 模拟量 -->

        <!-- 数量 -->
        <number v-if="selectedKey === '2'" ref="numberRef" />
        <!-- 数量 -->

        <!-- 字符串 -->
        <template v-if="selectedKey === '3'">
          <!-- 定值 -->
          <fixedValue ref="fixedValueRefByStr" />
          <!-- 变化 -->
          <variety ref="varietyRef" />
        </template>
        <!-- 字符串 -->
      </div>
      <div
        class="btn-box"
        v-if="['1', '2', '3'].indexOf(selectedKey) >= 0 && hasPermission('11-1-addRule')"
      >
        <a-button class="btns-one" @click="closeDrawer">取消</a-button>
        <a-button type="primary" @click="throttleSubmit" :loading="loading">提交</a-button>
      </div>
    </div>
  </BasicDrawer>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicDrawer } from '/@/components/Drawer';
  import limitValue from '/@/views/project/alertRules/components/limitValue.vue';
  import fixedValue from '/@/views/project/alertRules/components/fixedValue.vue';
  import deviation from '/@/views/project/alertRules/components/deviation.vue';
  import changeRateForm from '/@/views/project/alertRules/components/changeRateForm.vue';
  import number from '/@/views/project/alertRules/components/number.vue';
  import variety from '/@/views/project/alertRules/components/variety.vue';
  import {
    getalarmruledetail,
    editalarmruledetail,
    deletealarmruledetail,
  } from '/@/api/alertRules/index';
  import { useDebounceFn } from '@vueuse/core';
  import { computed, ref, reactive } from 'vue';
  import { useDrawer } from '/@/components/Drawer';
  import { itemsModel } from '../type';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const { t } = useI18n();
  const { hasPermission } = usePermission();
  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  let varietyRef = ref<any>();
  let fixedValueRefByStr = ref<any>();
  let numberRef = ref<any>();
  let changeRateFormRef = ref<any>();
  let deviationRef = ref<any>();
  let fixedValueRefBySimulation = ref<any>();
  let limitValueRef = ref<any>();

  let loading = ref(false);
  let selectedKey = ref('');
  let items: itemsModel[] = reactive([]);
  let drawerTitle = computed(() => {
    return `告警规则（${props.info.data.Name}）`;
  });
  const throttleSubmit = useDebounceFn(handleSubmint, 500);
  const [register, { closeDrawer }] = useDrawer();
  function getDelDateParams(alarmRuleName, list) {
    return list.map((item) => {
      return {
        groupName: props.info.data.GroupKey,
        alarmItemName: props.info.data.Name,
        alarmRuleName,
        ruleTypeUuid: item,
      };
    });
  }
  // 0.AnalogLimit,1.AnalogDeviation,2.AnalogCondition,3.AnalogRate,4.Digitalpreset,5.StringPreset,6.StringChanged
  async function getParamsBySimulation() {
    try {
      let valByChangeRateForm = await changeRateFormRef.value.getValue();
      let valByDeviationObj = await deviationRef.value.getValue();
      let valByFixedValueObj = await fixedValueRefBySimulation.value.getValue();
      let valByLimitObj = await limitValueRef.value.getValue();
      let params = [
        {
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'AnalogRate',
          alarmRuleType: 3,
          alarmDetailParams: valByChangeRateForm,
        },
      ];
      if (valByLimitObj.tableData.length > 0) {
        params.push({
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'AnalogLimit',
          alarmRuleType: 0,
          alarmDetailParams: valByLimitObj.tableData,
        });
      }
      if (valByDeviationObj.tableData.length > 0) {
        params.push({
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'AnalogDeviation',
          alarmRuleType: 1,
          alarmDetailParams: valByDeviationObj.tableData,
        });
      }
      if (valByFixedValueObj.tableData.length > 0) {
        params.push({
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'AnalogCondition',
          alarmRuleType: 2,
          alarmDetailParams: valByFixedValueObj.tableData,
        });
      }

      let delByLimit = getDelDateParams('AnalogLimit', valByLimitObj.delData);
      let delByDeviation = getDelDateParams('AnalogDeviation', valByDeviationObj.delData);
      let delByFixedValue = getDelDateParams('AnalogCondition', valByFixedValueObj.delData);
      let totalDelParams = [...delByLimit, ...delByDeviation, ...delByFixedValue];
      submitApi(params, totalDelParams);
    } catch (error) {}
  }
  async function getParamsByNumber() {
    try {
      let valByNumber = await numberRef.value.getValue();
      let params = [
        {
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'Digitalpreset',
          alarmRuleType: 4,
          alarmDetailParams: valByNumber,
        },
      ];
      submitApi(params);
    } catch (error) {}
  }
  async function getParamsByStr() {
    try {
      let valByFixedValueObj = await fixedValueRefByStr.value.getValue();
      let valByVariety = await varietyRef.value.getValue();
      let params = [
        {
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'StringChanged',
          alarmRuleType: 6,
          alarmDetailParams: valByVariety,
        },
      ];
      if (valByFixedValueObj.tableData.length > 0) {
        params.push({
          groupName: props.info.data.GroupKey,
          alarmItemName: props.info.data.Name,
          alarmRuleName: 'StringPreset',
          alarmRuleType: 5,
          alarmDetailParams: valByFixedValueObj.tableData,
        });
      }

      let delByFixedValue = getDelDateParams('StringPreset', valByFixedValueObj.delData);
      submitApi(params, delByFixedValue);
    } catch (error) {}
  }
  async function submitApi(params, delParams = []) {
    try {
      loading.value = true;
      if (delParams.length > 0) await deletealarmruledetail([delParams]);
      await editalarmruledetail([params]);
      createMessage.success(t('layout.setting.operatingTitle'));
      loading.value = false;
      closeDrawer();
    } catch (error) {
      loading.value = false;
    }
  }
  // 提交事件
  function handleSubmint() {
    switch (selectedKey.value) {
      case '1':
        getParamsBySimulation();
        break;
      case '2':
        getParamsByNumber();
        break;
      case '3':
        getParamsByStr();
        break;
    }
  }
  function getSetValueParams(res) {
    let targetObj = {
      '1': [0, 1, 2, 3],
      '2': [4],
      '3': [5, 6],
    };
    let targets = targetObj[selectedKey.value];
    let obj = {};
    res.forEach((v) => {
      if (targets.indexOf(v.AlarmType) >= 0) {
        obj[v.AlarmType] = v.DetailRuleItem;
      }
    });
    return obj;
  }
  // 获取详情
  async function getInfo(val) {
    let res = await getalarmruledetail([val.GroupKey, val.Name]);
    let resData = Array.isArray(res) ? res : [];
    let paramObj = getSetValueParams(resData);
    switch (selectedKey.value) {
      case '1':
        changeRateFormRef.value.setValue(paramObj[3] || []);
        deviationRef.value.setValue(paramObj[1] || []);
        fixedValueRefBySimulation.value.setValue(paramObj[2] || []);
        limitValueRef.value.setValue(paramObj[0] || []);
        break;
      case '2':
        numberRef.value.setValue(paramObj[4] || []);
        break;
      case '3':
        fixedValueRefByStr.value.setValue(paramObj[5] || []);
        varietyRef.value.setValue(paramObj[6] || []);
        break;
    }
  }
  // 显示回调
  async function handleVisibleChange(visible) {
    if (visible) {
      // 显示
      let menus: itemsModel[] = [
        {
          key: '1',
          label: '模拟量',
          rule: [3, 4, 5, 6, 7, 8],
        },
        {
          key: '2',
          label: '数字',
          rule: [1],
        },
        {
          key: '3',
          label: '字符串',
          rule: [11],
        },
      ];
      items = menus.filter((item) => item.rule.indexOf(props.info.data.DataType) >= 0);
      selectedKey.value = items.length > 0 ? items[0].key : '';
      getInfo(props.info.data);
    } else {
      //关闭
    }
  }
  // 菜单点击
  function handleMenuClick(val) {
    selectedKey.value = val;
  }
</script>

<style scoped lang="less">
  .scrollbar__view {
    height: 100% !important;
    position: relative;
  }

  .rules-box {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    display: flex;

    .menu {
      height: 100%;
      width: 150px;
      border-right: 1px solid #ccc;

      .menu-item {
        height: 40px;
        line-height: 40px;
        padding-inline: 16px;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-inline: 4px;
        margin-block: 4px;
        width: calc(100% - 8px);
        color: #000;
        border-radius: 8px;
        cursor: pointer;
        transition: border-color 0.3s, background 0.3s,
          padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      }

      .menu-item:hover {
        background-color: #f0f0f0;
      }

      .menu-item-act {
        background-color: #e6f4ff;
        color: #1677ff;
      }
    }

    .form-box {
      flex: 1;
      height: 100%;
      // padding: 10px 10px;
      box-sizing: border-box;
      overflow-y: auto;
      position: relative;
      padding-bottom: 52px;
    }

    .btn-box {
      position: absolute;
      left: 150px;
      right: 0;
      bottom: 0;
      background-color: #fff;
      z-index: 999;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 10px 10px;
      box-sizing: border-box;

      .btns-one {
        margin-right: 20px;
      }
    }
  }
</style>
